//1.安装sequelize库 npm install --save sequelize
//2.安装mysql驱动库 npm install --save mysql2
const { Sequelize, DataTypes } = require('sequelize'); //3.导包
//4.实例化Sequelize，完成链接配置
const sequelize = new Sequelize('node', 'root', '123456', {
  //连接选项
  host: 'localhost', // 数据库地址
  dialect: 'mysql', // 指定连接的数据库类型
  dialectOptions: { charset: "utf8mb4" },
  'define': {
    'underscored': true,//字段下划线
    'charset': 'utf8mb4',//必须设置了才能保存中文
    'freezeTableName': true//所有表将使用与模型名称相同的名称
  },
  pool: {
    max: 5, // 连接池的最大连接数量
    min: 0, // 连接池的最小连接数量
    idle: 10000 // 如果一个线程10秒钟内没有被使用，那么就释放线程
  }
});
const StudentModel = sequelize.define('Student', {
    studentId: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
      },
  sname: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  sex: {
    type: DataTypes.STRING,
  },
},
  {
    tableName: 'students',
  }
);

const GradeModel = sequelize.define('grade', {
  score: {
    type: DataTypes.INTEGER,
  },
},
  {
    tableName: 'grade',
  }
);

(async function () {

  // DepartmentModel.hasMany(EmployeeModel)
  // EmployeeModel.belongsTo(DepartmentModel)

  StudentModel.hasMany(GradeModel, { foreignKey: 'Grade_Student_id', sourceKey: 'studentId' })
  GradeModel.belongsTo(StudentModel, { foreignKey: 'Grade_Student_id', targetKey: 'studentId' })

  await StudentModel.sync({ force: true }).then(() => {
    console.log('成功创建students表')
  })
  await GradeModel.sync({ force: true }).then(() => {
    console.log('成功创建grade表')
  })

  const student = await StudentModel.create({ sname: '张三' ,sex:"男"})
  const grade = await GradeModel.create({ score:80 })
grade.setStudent(student)
})()